<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Vue CDN示例</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-size: 14px; }
    </style>
    <link rel="stylesheet" href="index.css">
    <!-- 引入vant样式文件 -->
    <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/vant@4/lib/index.css"
    />
</head>
<body>
    <div id="app">
        <router-view></router-view>
    </div>

    <!-- CDN 引入 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>

    <!-- 引入  Vant 的 JS 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/vant@4/lib/vant.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.2/echarts.min.js"></script>

    <!-- 引入dayjs的CDN -->
    <script src="https://unpkg.com/dayjs@1.11.10/dayjs.min.js"></script>

    <script>
        // 表单页组件
        const FormPage = {
            name: 'FormPage',
            template: `
                <div class="container">
                    <h2>我的记账本</h2>
                    <div class="plate plate_1">

                      <input v-model="remark" class="nostyle" type="text" placeholder="请输入账单来源或者用途">

                      <div class="money-box">
                        <div class="select-box">
                            <select class="nostyle" v-model="type">
                                <option value="income">收入</option>
                                <option value="expense">支出</option>
                            </select>
                        </div>
                        <input v-model="amount" class="nostyle money" type="number" placeholder="输入金额">
                      </div>

                      <div class="date-input" @click="show = true">日期：{{date}}</div>

                      <div class="tags">
                        <div class="tag " :class="{'selected': selected === cat}" @click="choose(cat)" v-for="cat in categorys">{{cat}}</div>
           
                      </div>

                      <div class="submit" @click="submit">录入</div>

                    </div>

                    <div class="plate plate_2">
                        <div class="scroll">
                            <div class="list">
                                <div class="li li-1" 
                                :class="{'shouru': li.type === 'income', 'zhichu': li.type === 'expense'}" 
                                v-for="li in list"
                                :key="li.id"
                                >
                                    <div class="type">
                                        <div class="text">{{thyeF(li.type)}}</div>    
                                        <div class="date">{{li.date}}</div>
                                    </div>
                                    <div class="des">{{li.remark }}</div>
                                    <div class="cost">{{li.amount}}元</div>
                                </div>
                                <div class="zhanwei"></div>
                            </div>    
                        </div>
                    </div>

                    <router-link class="more" to="/stats">
                        更多账单 >
                    </router-link>
                    <van-calendar 
                    :min-date="dayjs().subtract(1, 'month').toDate()" 
                    :max-date="dayjs().toDate()"
                    v-model:show="show" @confirm="onConfirm" />

                </div>
            `,
            data() {
                return { 
                    dayjs: dayjs,
                    show: false,
                    date: dayjs().format('YYYY-MM-DD'),
                    incomeCategorys: ['工资', '理财', '电商', '转账', '其他'],
                    expenseCategorys: ['服饰', '食物', '出行', '教育', '住房', '其他'],
                    type: 'income',
                    remark: '',
                    amount: '',
                    selected: '',       //选中的分类
                    list: [],           // 列表数据
                }
            },
            computed: {
                categorys (value) {
                    return this.type === 'income' ? this.incomeCategorys : this.expenseCategorys;
                },
            },
            beforeMount () {
                this.getList();
            },
            
            methods: {
                thyeF (type) {
                    if (type === 'income') {
                        return '收入'
                    } else if (type === 'expense') {
                        return '支出'
                    }
                },
                choose (cat) {
                    this.selected = cat;
                },
                onConfirm (date) {
                    // 使用dayjs格式化日期
                    this.date = dayjs(date).format('YYYY-MM-DD');
                    this.show = false;
                },
                getList () {
                    axios.get('http://127.0.0.1:5000/records', {
                        params: {
                            start_date: dayjs().subtract(7, 'day').format('YYYY-MM-DD')
                        }
                    }).then(res => {
  
                        if (res.data.success) {
                            this.list = res.data.data;
                        }
                    })
                },
                submit () {
                    if (!this.remark) {
                        vant.showToast('请填写备注');
                        return
                    } else if (!this.amount) {
                        vant.showToast('请填写金额');
                        return
                    } else if(!this.selected) {
                        vant.showToast('请选择分类');
                        retrun
                    } else if (! /^[+]?([1-9]\d*|0)(\.\d+)?$/.test(this.amount)) {
                        vant.showToast('金额格式错误');
                        return 
                    }
                    axios.post('http://127.0.0.1:5000/records', {
                        type: this.type,
                        remark: this.remark,
                        amount: this.amount,
                        date: this.date,
                        category: this.selected
                    }).then(res => {
                        if(res.data.success) {
                            this.remark = '';
                            this.amount = '';
                            this.getList();
                        }
                        vant.showToast(res.data.message);
                    })
                },
            }
        }

        // 统计页组件
        const StatsPage = {
            name: 'StatsPage',
            template: `<div class="container stats-page">
                         <router-link to="/form" class="back"><img src="./images/back.png" /></router-link>
                         <div class="dates">
                            <div class="date" :class="{'selected': selectedDate === 1}" @click="selecte(1)">7天</div>
                            <div class="date" :class="{'selected': selectedDate === 2}" @click="selecte(2)">本月</div>
                            <div class="date" :class="{'selected': selectedDate === 3}" @click="selecte(3)">30天</div>
                            <div class="date" :class="{'selected': selectedDate === 4}" @click="selecte(4)">今年</div>
                         </div>
                         <div class="echar-box">
                            <div class="echar echar-shouru" id="echar-shouru"></div>
                            <div class="echar echar-zhichu" id="echar-zhichu"></div>
                         </div>
                         <div class="total-box">
                            <div class="total total-shouru">总收入：{{shouruTotal}}元</div>
                            <div class="total total-zhichu">总支出：{{zhichuTotal}}元</div>
                         </div>

                        <div class="plate plate_2">
                            <div class="scroll">
                                <div class="list">
                                    <div class="li shouru" 
                                    :class="{'shouru': li.type === 'income', 'zhichu': li.type === 'expense'}" 
                                    v-for="li in list"
                                    :key="li.id"
                                    >
                                        <van-swipe-cell >
                                            <div class="li-inner">
                                                <div class="type">
                                                    <div class="text">{{thyeF(li.type)}}</div>    
                                                    <div class="date">{{li.date}}</div>
                                                </div>
                                                <div class="des">{{li.remark}}</div>
                                                <div class="cost cost-2">{{li.amount}}元</div>
                                            </div>
                                            <template #right>
                                                <van-button @click="delOne(li.id)" square text="删除" type="danger" class="delete-button" />
                                            </template>
                                        </van-swipe-cell>

                                    </div>
                                    <div class="zhanwei"></div>
                                </div>    
                            </div>
                        </div>

                       </div>`,
            data() {
                return {
                    selectedDate: null,
                    list: [],
                    incomeList: [],
                    expenseList: [],
                    dayjs: dayjs, 
                    shouruTotal: 0,
                    zhichuTotal: 0
                }
            },
            mounted() {
                this.selecte(1);
            },
            methods: {
                delOne (id) {
                    console.log('id', id)
                    axios.post('http://127.0.0.1:5000/records/delete', {
                        id: id
                    }).then(res => {
                        vant.showToast(res.data.message);
                        if (res.data.success) {
                            this.getList();
                        }
                    })
                },
                thyeF (type) {
                    if (type === 'income') {
                        return '收入'
                    } else if (type === 'expense') {
                        return '支出'
                    }
                },
                selecte (value) {
                    this.selectedDate = value;
                    this.getList()
                },
                getStartDate() {
                    let startDate = '';
                    if (this.selectedDate === 1) {
                        startDate = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
                    } else if (this.selectedDate === 2) {
                        startDate = dayjs().startOf('month').format('YYYY-MM-DD');
                    }   else if (this.selectedDate === 3) {
                        startDate = dayjs().subtract(30, 'day').format('YYYY-MM-DD');
                    } else if (this.selectedDate === 4) {
                        startDate = dayjs().startOf('year').format('YYYY-MM-DD');
                    }
                    return startDate;
                },
                getList () {
                    const startDate = this.getStartDate();
                    axios.get('http://127.0.0.1:5000/records', {
                        params: {
                            start_date: startDate
                        }
                    }).then(res => {
  
                        if (res.data.success) {
                            this.list = res.data.data;
                            this.incomeList = this.list.filter(item => item.type === 'income');
                            this.expenseList = this.list.filter(item => item.type === 'expense');
                
                            this.rendShouru(this.incomeList);
                            this.rendZhichu(this.expenseList);

                            this.shouruTotal = this.getTotalAmount(this.incomeList).toFixed(2);
                            this.zhichuTotal = this.getTotalAmount(this.expenseList).toFixed(2);

                        }
                    })
                },
                listHandler (list) {
                    const obj = {};
                    list.forEach(item => {
                        if (!obj[item.category]) {
                            obj[item.category] = []
                            obj[item.category].push(item);
                        } else {
                            obj[item.category].push(item);
                        }
                    })
                   
                    let arr = []
                    Object.keys(obj).forEach(key => {
                        arr.push({
                            name: key,
                            value: obj[key].length
                        })
                    })
                    return arr
                },
                getTotalAmount (list) {
                    let total = 0;
                    list.forEach(item => {
                        total += item.amount;
                    })
                    return total;
                },
                rendShouru (incomeList) {
                    const data = this.listHandler(incomeList);
                    const chart = echarts.init(document.getElementById('echar-shouru'));
                    const option = {
                        title: {
                            text: '收入',
                            left: 'center',
                            top: '5px',
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        series: [
                            {
                            type: 'pie',
                            radius: '50%',
                            label: {
                                fontSize: 10,
                                // 添加 formatter 属性以显示百分比
                                formatter: '{b}:\n{d}%' 
                            },
                            labelLine: {
                                length: 0,
                                length2: 0
                            },
                            data: data,
                            emphasis: {
                                    itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]

                    };
                    chart.setOption(option);
                },
                rendZhichu (expenseList) {
                    const data = this.listHandler(expenseList);
                    const chart2 = echarts.init(document.getElementById('echar-zhichu'));
                    const option2 = {
                        title: {
                            text: '支出',
                            left: 'center',
                            top: '5px',
                            textStyle: {
                                fontSize: 12
                            }
                        },
    
                        series: [
                            {
                            type: 'pie',
                            radius: '50%',
                            label: {
                                fontSize: 10,
                                // 添加 formatter 属性以显示百分比
                                formatter: '{b}:\n{d}%' 
                                
                            },
                            labelLine: {
                                length: 0,
                                length2: 0
                            },
                            data: data,
                            emphasis: {
                                    itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]

                    };
                    chart2.setOption(option2);

                }

            }
        }

        // 路由配置
        const router = VueRouter.createRouter({
            history: VueRouter.createWebHashHistory(),
            routes: [
                { path: '/form', component: FormPage },
                { path: '/stats', component: StatsPage },
                { path: '/', redirect: '/form' }
            ]
        });

        // 初始化Vue应用
        const app = Vue.createApp({});
        app.use(vant);
        app.use(router);
        app.mount('#app');
    </script>
</body>
</html>